<template>
  <a-form
    @submit="onSubmit"
    :form="form"
    name='addAct'
  >
    <!-- 活动标题 -->
    <a-form-item
      v-bind="formItemLayout"
      label="活动标题"
    >
      <a-input
        v-decorator="[
          `name`,
          {
            rules: [{
              required: true,
              message: '不能为空!',
            }],
          }
        ]"
        placeholder="请添加总活动标题"
      />
    </a-form-item>
    <!-- 原始价格 -->
    <a-form-item
      v-bind="formItemLayout"
      label="原始价格"
    >
      <a-input
        v-decorator="[
          `price`,
          {
            rules: [{
              required: true,
              message: '不能为空!',
            }],
          }
        ]"
        placeholder="活动原始价格"
      />
    </a-form-item>
    <!-- 活动价格 -->
    <a-form-item
      v-bind="formItemLayout"
      label="活动价格"
    >
      <a-input
        v-decorator="[
          `payprice`,
          {
            rules: [{
              required: true,
              message: '不能为空!',
            }],
          }
        ]"
        placeholder="活动折扣价格"
      />
    </a-form-item>
    <!-- 联系人 -->
    <a-form-item
      v-bind="formItemLayout"
      label="联系人"
    >
      <a-input
        v-decorator="[
          `linkman`,
          {
            rules: [{
              required: true,
              message: '不能为空!',
            }],
          }
        ]"
        placeholder="请添加联系人"
      />
    </a-form-item>
    <!-- 联系方式 -->
    <a-form-item
      v-bind="formItemLayout"
      label="联系方式"
    >
      <a-input
        v-decorator="[
          `phone`,
          {
            rules: [{
              required: true,
              message: '不能为空!',
            }],
          }
        ]"
        placeholder="请添加联系方式"
      />
    </a-form-item>
    <!-- 活动日期 -->
    <a-form-item
      v-bind="formItemLayout"
      label="活动日期"
    >
      <a-range-picker
        v-decorator="['acttime', rangeConfig]"
        show-time
        :format="dateFormat"
        :placeholder="['活动开始日期', '活动结束日期']"
      />
      <!-- 
        :defaultValue="[moment(starttime, dateFormat), moment(endtime, dateFormat)]" -->
    </a-form-item>
    <!-- 展示图上传 500x350 -->
    <a-form-item
      v-bind="formItemLayout"
      label="活动展示图"
    >
      <div class="clearfix">
        <a-upload
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          listType="picture-card"
          :fileList="fileList"
          @preview="handlePreview"
          @change="handleChange"
        >
          <div v-if="fileList.length < 3">
            <a-icon type="plus" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        <a-modal
          :visible="previewVisible"
          :footer="null"
          @cancel="handleCancel"
        >
          <img
            alt="example"
            style="width: 100%"
            :src="previewImage"
          />
        </a-modal>
      </div>
    </a-form-item>
    <!-- 活动主体内容 -->
    <a-form-item v-bind="formItemLayout" label='允许添加多个商家'>
      <!-- 已添加商家列表 -->
      <a-list
        bordered
        :dataSource="comActList"
       class="com-act-list">
        <a-list-item slot="renderItem" slot-scope="item, index" :key="index">
          <a slot="actions" @click='modActCom(index)'>修改</a>
          <a slot="actions" @click.stop='removeActCom(index)'><a-icon type="close-circle" /></a>
          <span class="com-name">「 {{item.comSelName||item.companyName}}」</span>
          <span>{{item.maintitle}}</span>
        </a-list-item>
        <div slot="header">已添加商家列表</div>
      </a-list>

      <a-button
        type="dashed"
        style="width: 100%"
        @click="addActCom"
      >
        <a-icon type="plus" />添加活动合作商家
      </a-button>
    </a-form-item>
    <!-- 添加商家弹框 -->
    <a-modal
      v-model="visible"
      title="添加商家宣传"
      @Ok="addActComOk"
      width='90%'
    >
    <template slot="footer">
      <a-button key="back" @click="cancleAddActCom">取消添加</a-button>
      <a-button key="actsubmit" type="primary" :loading="loading" @click="addActComOk">
        确认添加
      </a-button>
    </template>
    <!-- 添加商家宣传具体信息 -->
    <a-form 
    :form="actform"
    name='addCom'>
      <div>
        <a-form-item label='选择参与活动商家' v-bind="formItemLayout">
          <a-select
          v-decorator="[
              'companyid',
              {rules: [{ required: true, message: '请选择一个商家' }]}
            ]" @change="onComChange" style="width: 100%;z-index:20">
            <a-select-option v-for="(item) in comList" :key="item.id" :value="item.id">{{item&&item.name}}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label='商家活动标题' v-bind="formItemLayout">
          <a-input
            v-decorator="[
              'maintitle',
              {rules: [{ required: true, message: '请填写商家活动标题' }]}
            ]"
          />
        </a-form-item>
        <a-form-item label='商家活动导航关键词' v-bind="formItemLayout">
          <a-input
            v-decorator="[
              'subtitle',
              {rules: [{ required: true, message: '商家活动导航关键词' }]}
            ]"
          />
        </a-form-item>
        <!-- 商家活动宣传 -->
        <a-form-item label='商家活动宣传' v-bind="formItemLayout">
          <Editor :catchData="editorTxt" :content="editorEontent"/>
        </a-form-item>
        </div>
      </a-form> 
    </a-modal>
    <!-- 提交主体活动按钮 -->
    <div
      style="position:fixed;left:0;right:0;bottom:0;background:#fff;padding:8px">
      <a-button
        html-type="submit"
        type="primary"
      >提交活动</a-button>
    </div>
  </a-form>
</template>
<script>
import Editor from '@/components/editor/Editor'
import { Message } from 'ant-design-vue'
import moment from 'moment';
let id = 0;
export default {
  data() {
    return {
      actId:false,
      loading: false,//商家活动转换为数组
      visible: false,//添加商家宣传弹框
      editorEontent:'',//富文本编辑器返回内容
      comCallStyle://商家面板样式
        "background: #f7f7f7;border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden",
      previewVisible: false,//展示图预览
      previewImage: "",//展示图
      fileList: [],//缩略图列表
      comList:[],//商家下拉框列表
      comActList:[],//商家宣传列表
      comInfo:null,
      comCurrIndex:null,//当前正在编辑商家
      rangeConfig: {//时间选择插件
        rules: [{ type: "array", required: true, message: "请选择起止日期" }]
      },
      starttime:'',
      endtime:'',
      dateFormat:'YYYY-MM-DD HH:mm:ss',
      formItemLayout: {//表格样式
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 }
        }
      }
    };
  },
  methods: {
    //添加活动商家成功
    addActComOk(e){
      let vo = this;
      vo.loading = true;
      vo.actform.validateFields((err, fieldsValue) => {
        if (!err) {
          let values = {
            ...fieldsValue,
            txt :vo.editorEontent,
            comSelName:vo.comSelName,
          }
          if(vo.comCurrIndex==null){//修改数据
            console.log('添加数据');
            vo.comActList.push(values);
            vo.loading = false;
            vo.visible = false;
          }else{//添加数据
            console.log('修改数据');
            vo.comActList[vo.comCurrIndex] = Object.assign({},values);
            vo.loading = false;
            vo.visible = false;
            vo.comCurrIndex =null;
          }
        }
      });
    },
    // 修改活动商家
    modActCom  (i) {
      let vo = this;
      vo.comCurrIndex = i;
      let o = Object.assign({},vo.comActList[i]);
      vo.visible = true;//显示弹框
      this.$nextTick(() => {
        vo.actform.setFieldsValue({
          maintitle:o.maintitle,
          subtitle:o.subtitle,
          companyid:o.companyid
        }) 
      });
      vo.onComChange(o.companyid);
      vo.editorEontent = o.txt;
    },
    // 移除活动商家
    removeActCom  (i) {
      let vo = this;
      if(vo.comActList.length==1){
        vo.comActList = [];
      }else{
        let arr = [...vo.comActList];
        arr.splice(i,1);
        vo.comActList = [...arr];
      }
    },
    // 提交整个活动
    onSubmit(e) {
      let vo = this;
      e.preventDefault();
      vo.form.validateFields((err, fieldsValue) => {
        if (!err) {
          // 活动日期format
          const rangeTimeValue = fieldsValue["acttime"];
          const values = {
            ...fieldsValue,
            acttime: [
              rangeTimeValue[0].format("YYYY-MM-DD HH:mm:ss"),
              rangeTimeValue[1].format("YYYY-MM-DD HH:mm:ss")
            ],
            imgList:vo.fileList.slice(),
            comActList:[...vo.comActList].map((o)=>{
              o = Object.assign({},o);
              delete o['comSelName'];
              return o;
            })
          };
          // console.log(values.imgList);
          if(vo.actId){//修改
            values.id = vo.actId;
            let dataUrl = `backstage/updActivity.do`;
            vo.ajax.post(dataUrl, values).then(res => {
              if(res==1){//活动添加成功
                Message.success('活动修改成功');
                vo.$router.push('/actmanage');
              }
            });
          }else{
            let dataUrl = `backstage/addActivity.do`;
            vo.ajax.post(dataUrl, values).then(res => {
              if(res==1){//活动添加成功
                Message.success('活动添加成功');
                vo.$router.push('/actmanage');
              }
            });
          }
        }
      });
    },
    // 富文本编辑器
    editorTxt(txt){//商家宣传内容
      this.editorEontent = txt;
    },
    // 添加活动商家
    addActCom(){
      this.visible = true;//显示弹框
    },
    // 取消添加商家
    cancleAddActCom(){
      this.visible = false;
    },
    // 取消缩略图预览
    handleCancel() {
      this.previewVisible = false;
    },
    // 缩略图预览
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    // 缩略图上传
    handleChange({file,fileList }) {
      let vo = this;
      let arr = fileList.slice();
      let brr = arr.map((v)=>{
        if(v.thumbUrl){
          let o = {
            name: v.name,
            url: v.thumbUrl,
            status:v.status,
            uid :v.uid
          }
          return o
        }else{
          return v;
        }
      })
      vo.fileList = brr;
      console.log(`~~~~~~~~~~~~~~~`);
      console.log(brr);
    },
    // 选择商家
    onComChange(id){
      let vo=this,com = vo.comList.filter((v)=>{
        return v.id == id
      })
      console.log(vo.comList,id);
      vo.comSelName =  com[0]&&com[0].name;
    },
    //修改活动初始化
    initModData(id){
      let vo = this;
      vo.initData();
      vo.actId = id;
      const dataUrl = `backstage/queryActivityById.do?id=${id}`
      vo.ajax.get(dataUrl).then(res => {
        let o = res.data.info;
        vo.comInfo = o;//要修改的商家信息
        console.log(o);
        vo.form.setFieldsValue({
          name: o.name,
          price:o.price,
          payprice:o.payprice,
          linkman: o.linkman,
          phone: o.phone,
          acttime:[moment(o.starttime,'YYYY-MM-DD HH:mm:ss'),moment(o.endtime,'YYYY-MM-DD HH:mm:ss')]
        });
        vo.fileList = [...o.imgList];
        console.log(o);
        //2019-8-14 ??
        vo.comActList = o.comActList;
      });
    },
    //添加活动初始化
    initData(){
      let vo = this;
      vo.actId = false;
      const dataUrl =`backstage/selAllCompany.do`;
      vo.ajax.get(dataUrl).then(res => {
        vo.comList = res.data;
      });
    },
    moment
  },
  beforeCreate () {
    this.form = this.$form.createForm(this);
    this.form.getFieldDecorator('keys', { initialValue: [], preserve: true });
    
    this.actform = this.$form.createForm(this);
    this.form.getFieldDecorator('keys', { initialValue: [], preserve: true });
  },
  mounted(){
    let q = this.$route.query;
    if(Object.keys(q).length>0){//修改
      this.initModData(q.id);
    }else{//添加
      this.initData();
    }
  },
  components:{
    Editor
  }
};
</script>
<style>
.ant-layout-content {
  position: relative;
}
.ant-calendar-picker {
  width: 100% !important;
}
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
/* 已添加商家列表 */
.com-act-list .com-name{
  margin-right: 10px;
    font-weight: bold;
    color: #666;
}
</style>
